from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from WebSite.models.AppModel import TUser
from WebSite.views.auth import Auth
from WebSite.views.exceptions import AppException
from WebSite.views.misc import strtomd5
from WebSite.views.utl import GetJsonResponse
from predict.settings import SESSION_KEY_CAPTCHA


def parse_post(request, key, default=None):
	value = request.POST.get(key, None)
	if value == default:
		raise AppException("缺少" + key)
	return value


@csrf_exempt
def user_register(request):
	user_name = parse_post(request, 'user_name')
	pwd = parse_post(request, 'pwd')
	verifycode = parse_post(request, 'verifycode')

	session_code = request.session.get(SESSION_KEY_CAPTCHA, None)
	if verifycode.lower() != session_code.lower():
		return GetJsonResponse({"error": "验证码错误"})
	user = TUser.objects.filter(user_name=user_name).first()
	if user is not None:
		return GetJsonResponse({"error": "用户名已存在"})

	TUser.objects.create(user_name=user_name, pwd=strtomd5(pwd))
	user = Auth.authenticate(username=user_name, password=pwd)
	Auth.login(request, user)

	return GetJsonResponse({"result": "OK", 'url': reverse("index")})


def user_login(request):
	if request.method == 'GET':
		return render(request, 'app/login.html')
	elif request.method == 'POST':
		username = request.POST.get('user_name', None)
		password = request.POST.get('pwd', None)
		captcha_code = request.POST.get('verifycode', None)
		session_captcha_code = request.session.get(SESSION_KEY_CAPTCHA, None)
		assert username is not None, password is not None

	if captcha_code is None or session_captcha_code is None or captcha_code.lower() != session_captcha_code.lower():
		return GetJsonResponse({'error': '验证码错误'})
	# 清理验证码
	request.session[SESSION_KEY_CAPTCHA] = None

	try:
		user = Auth.authenticate(username=username, password=password)
		Auth.login(request, user)  # store information in session variables
		# 转到成功页面
		return GetJsonResponse({'result': 'OK', 'url': reverse("index")})
	except AppException as e:
		return GetJsonResponse({'error': str(e)})
	except Exception as e:
		return GetJsonResponse({'error': '认证失败，系统错误'})
